
package com.example.demo.util.rsa;

import com.example.demo.util.TextUtils;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.List;

/**
 * RSA解密
 */

public class RSADecryptUtils {
    /**
     * 非对称加密密钥算法
     */
    static final String RSA = "RSA";

    /**
     * 加密填充方式
     */
    static final String ECB_PKCS1_PADDING = "RSA/ECB/PKCS1Padding";

    /**
     * 当要加密的内容超过bufferSize，则采用partSplit进行分块加密
     */
    static final byte[] DEFAULT_SPLIT = "#PART#".getBytes();

    /**
     * 将字符串形式的公钥转换为公钥对象
     *
     * @param strKey
     * @return
     */
    static PublicKey strKey2PublicKey(String strKey) {
        if (TextUtils.isEmpty(strKey)) {
            return null;
        }
        PublicKey _PublicKey = null;
        byte[] keyBytes = Base64.decode(strKey, Base64.DEFAULT);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        try {
            KeyFactory keyFactory = KeyFactory.getInstance(RSA);
            _PublicKey = keyFactory.generatePublic(keySpec);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        }
        return _PublicKey;
    }

    /**
     * 公钥解密
     *
     * @param data 待解密数据
     * @param publicKey 密钥
     * @return byte[] 解密数据
     */
    static byte[] decryptByPublicKey(byte[] data, byte[] publicKey) throws Exception {
        if (data == null || publicKey == null) {
            return null;
        }
        // 得到公钥
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
        KeyFactory kf = KeyFactory.getInstance(RSA);
        PublicKey keyPublic = kf.generatePublic(keySpec);
        // 数据解密
        Cipher cipher = Cipher.getInstance(ECB_PKCS1_PADDING);
        cipher.init(Cipher.DECRYPT_MODE, keyPublic);
        return cipher.doFinal(data);
    }

    /**
     * 公钥分段解密
     *
     * @param encrypted 待解密数据
     * @param publicKey 密钥
     */
    static byte[] decryptByPublicKeyForSpilt(byte[] encrypted, byte[] publicKey) throws Exception {
        if (encrypted == null || publicKey == null) {
            return null;
        }
        int splitLen = DEFAULT_SPLIT.length;
        if (splitLen <= 0) {
            return decryptByPublicKey(encrypted, publicKey);
        }
        int dataLen = encrypted.length;
        List<Byte> allBytes = new ArrayList<>(1024);
        int latestStartIndex = 0;
        for (int i = 0; i < dataLen; i++) {
            byte bt = encrypted[i];
            boolean isMatchSplit = false;
            if (i == dataLen - 1) {
                // 到data的最后了
                byte[] part = new byte[dataLen - latestStartIndex];
                System.arraycopy(encrypted, latestStartIndex, part, 0, part.length);
                byte[] decryptPart = decryptByPublicKey(part, publicKey);
                for (byte b : decryptPart) {
                    allBytes.add(b);
                }
                latestStartIndex = i + splitLen;
                i = latestStartIndex - 1;
            } else if (bt == DEFAULT_SPLIT[0]) {
                // 这个是以split[0]开头
                if (splitLen > 1) {
                    if (i + splitLen < dataLen) {
                        // 没有超出data的范围
                        for (int j = 1; j < splitLen; j++) {
                            if (DEFAULT_SPLIT[j] != encrypted[i + j]) {
                                break;
                            }
                            if (j == splitLen - 1) {
                                // 验证到split的最后一位，都没有break，则表明已经确认是split段
                                isMatchSplit = true;
                            }
                        }
                    }
                } else {
                    // split只有一位，则已经匹配了
                    isMatchSplit = true;
                }
            }
            if (isMatchSplit) {
                byte[] part = new byte[i - latestStartIndex];
                System.arraycopy(encrypted, latestStartIndex, part, 0, part.length);
                byte[] decryptPart = decryptByPublicKey(part, publicKey);
                for (byte b : decryptPart) {
                    allBytes.add(b);
                }
                latestStartIndex = i + splitLen;
                i = latestStartIndex - 1;
            }
        }
        byte[] bytes = new byte[allBytes.size()];
        {
            int i = 0;
            for (Byte b : allBytes) {
                bytes[i++] = b.byteValue();
            }
        }
        return bytes;
    }

    // /**
    // * RSA公钥解密(速度快)
    // *
    // * @return
    // */
    // public static String decryptPublic(String encryText) {
    // return decryptPublic(KEY_STR_PUBLIC, encryText);
    // }

    /**
     * RSA公钥解密(速度快)
     *
     * @return
     */
    public static String decryptPublic(String key, String encryText) {
        if (encryText == null) {
            return null;
        }
        byte[] decryptBytes = new byte[0];
        try {
            PublicKey _PublicKey = strKey2PublicKey(key);
            if (_PublicKey == null) {
                return null;
            }
            decryptBytes = decryptByPublicKeyForSpilt(Base64.decode(encryText, Base64.DEFAULT),
                    _PublicKey.getEncoded());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new String(decryptBytes);
    }
}
